import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:hm_pda_app/config/http_request.dart';
import 'package:hm_pda_app/components/loading_overlay.dart';

class PendingDelivery extends StatefulWidget {
  const PendingDelivery({super.key});
  @override
  State<PendingDelivery> createState() => _PendingDeliveryState();
}

class _PendingDeliveryState extends State<PendingDelivery> {
  final _formKey = GlobalKey<FormState>(); // 表单Key
  final GlobalKey<_PendingDeliveryState> formKey =
      GlobalKey<_PendingDeliveryState>();
  // 文本控制器
  final _goodsReceiptController = TextEditingController();
  final _qualityInspectionController = TextEditingController();
  final _skuCodeController = TextEditingController();
  final _numberReceiptController = TextEditingController();
  final _actualQuantityReceived = TextEditingController();
  final _goodReceiptFocusNode = FocusNode();
  final _qualityInspectionFocusNode = FocusNode();
  final _numberReceiptFocusNode = FocusNode();
  final _actualQuantityReceivedFocusNode = FocusNode();
  final _skuCodeFocusNode = FocusNode();
  // 定义一个对象 - 可以根据实际需求调整
  PendingDeliveryData? _pendingDelivery;

  // 辅助方法：判断是否有有效的数据
  bool get _hasValidData => _pendingDelivery?.id?.isNotEmpty == true;
  // 选中的SKU项目
  PendingDeliveryData? _selectedSku;
  // sku列表
  List<PendingDeliveryData> skuDataList = <PendingDeliveryData>[];
  // 分页
  final ScrollController _scrollController = ScrollController(); // 创建滚动控制器
  bool _isLoading = false; // 是否正在加载更多数据
  int _pageNum = 1; // 当前页码，从0开始计数
  final int _pageSize = 50; // 每页显示的条目数
  num total = 0;
  // 初始化
  @override
  void initState() {
    super.initState();
    _pendingDelivery = PendingDeliveryData(
      id: '',
      incomingGoodsNo: '',
      qualityCheckNo: '',
      incomingGoodsUserName: '',
      qualityCheckUserName: '',
      skuCode: '',
      pictureUrlList: [],
    );
    _goodsReceiptController.text = _pendingDelivery?.incomingGoodsNo ?? '';
    _qualityInspectionController.text = _pendingDelivery?.qualityCheckNo ?? '';
    _goodReceiptFocusNode.requestFocus();
    // 初始化分页
    _fetchData(); // 初始化时加载数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      //_scrollController.addListener(_onScroll); // 添加滚动监听器
      print('🎯 滚动监听器已添加');
      _scrollController.addListener(_onScroll);
    });
  }

  void _onScroll() {
    // 添加基础的滚动检测
    print('🔄 滚动监听器被触发了！');
    if (_isLoading) return; // 防止重复加载

    final scrollPosition = _scrollController.position;
    final currentPixels = scrollPosition.pixels;
    final maxScrollExtent = scrollPosition.maxScrollExtent;
    final minScrollExtent = scrollPosition.minScrollExtent;

    // 计算滚动百分比
    final scrollPercentage = maxScrollExtent > 0
        ? (currentPixels / maxScrollExtent * 100).clamp(0.0, 100.0)
        : 0.0;

    // 监听滚动方向
    final scrollDirectionDta = scrollPosition.userScrollDirection;

    // 打印滚动信息
    print('📍 滚动位置: ${currentPixels.toStringAsFixed(1)}');
    print('📊 滚动百分比: ${scrollPercentage.toStringAsFixed(1)}%');
    print('🧭 滚动方向: ${_getScrollDirectionText(scrollDirectionDta)}');
    print('📏 最大滚动范围: ${maxScrollExtent.toStringAsFixed(1)}');

    // 检查是否滚动到顶部
    if (currentPixels <= minScrollExtent) {
      print('⬆️ 已滚动到顶部');
      _onScrollToTop();
    }

    // 检查是否滚动到底部
    if (currentPixels >= maxScrollExtent && !_isLoading) {
      print('⬇️ 已滚动到底部，开始加载更多数据');
      _onScrollToBottom();
      _fetchData(); // 滚动到底部时加载更多数据
    }

    // 检查是否滚动到中间位置
    if (scrollPercentage >= 45 && scrollPercentage <= 55) {
      _onScrollToMiddle();
    }

    // 检查快速滚动
    if (scrollPosition.activity?.velocity != null) {
      final velocity = scrollPosition.activity!.velocity;
      if (velocity.abs() > 1000) {
        // 滚动速度超过1000像素/秒
        print('⚡ 快速滚动中，速度: ${velocity.toStringAsFixed(1)} px/s');
        _onFastScroll(velocity);
      }
    }
  }

  // 获取滚动方向文本
  String _getScrollDirectionText(ScrollDirection direction) {
    switch (direction) {
      case ScrollDirection.forward:
        return '向下滚动';
      case ScrollDirection.reverse:
        return '向上滚动';
      case ScrollDirection.idle:
        return '停止滚动';
    }
  }

  // 滚动到顶部时的回调
  void _onScrollToTop() {
    // 可以在这里添加下拉刷新逻辑
    print('触发顶部事件');
  }

  // 滚动到底部时的回调
  void _onScrollToBottom() {
    // 可以在这里添加加载更多的UI提示
    print('触发底部事件');
  }

  // 滚动到中间位置时的回调
  void _onScrollToMiddle() {
    // 可以在这里添加中间位置的特殊逻辑
    // print('滚动到中间位置');
  }

  // 快速滚动时的回调
  void _onFastScroll(double velocity) {
    // 可以在这里添加快速滚动时的特殊处理
    print('快速滚动事件，速度: $velocity');
  }

  // 加载数据
  Future<void> _fetchData() async {
    setState(() {
      _isLoading = true;
    });
    try {
      final response = await HttpUtil.post(
        '/storage/receiveGoodsOperate/queryWaitingReceiveGoods?pageNum=$_pageNum&pageSize=$_pageSize',
        data: {
          'pageNum': _pageNum,
          'pageSize': _pageSize,
          "pageQuery": {'pageNum': _pageNum, 'pageSize': _pageSize},
        },
      );

      if (response.code == 200 && response.data != null) {
        setState(() {
          // 判断是否是一个map
          if (response.data is Map<String, dynamic>) {
            final dataMap = response.data as Map<String, dynamic>;
            total = dataMap['total'] ?? 0;
            if (dataMap['rows'] is List) {
              final List<dynamic> rowsList = dataMap['rows'];
              for (var item in rowsList) {
                if (item is Map<String, dynamic>) {
                  skuDataList.add(PendingDeliveryData.fromJson((item)));
                }
              }
            }
            _pageNum++; // 增加页码
            if (skuDataList.length >= total) {
              _scrollController.removeListener(_onScroll);
            }
            // skuDataList = dataList.map((item) => item.toJson()).toList();
            print(
              '待收货列表---${skuDataList.map((item) => item.toJson()).toList()}',
            );
            print('待收货列表---$skuDataList');
          }
        });
      }
      // 判断是否已经全部加载
      // if (response.data == null || skuDataList.length >= response.total) {
      //   // 已经加载完所有数据，可以设置一个标志位
      //   // 或者移除滚动监听器以避免继续触发加载
      //   return;
      // }
    } catch (e) {
      print('Error fetching data: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _selectItem(PendingDeliveryData item) {
    print('🎯 选中的SKU项目: ${item.toJson()}');

    setState(() {
      _goodsReceiptController.text = item.incomingGoodsNo ?? '';
      _qualityInspectionController.text = item.qualityCheckNo ?? '';
      _skuCodeController.text = item.skuCode ?? '';
      _pendingDelivery = PendingDeliveryData(
        id: item.id,
        incomingGoodsNo: item.incomingGoodsNo,
        qualityCheckNo: item.qualityCheckNo,
        incomingGoodsUserName: item.incomingGoodsUserName,
        qualityCheckUserName: item.qualityCheckUserName,
        skuCode: item.skuCode,
        pictureUrlList: item.pictureUrlList,
        actualReceiveNum: item.actualReceiveNum,
        expectReceiveNum: item.expectReceiveNum,
      );
      _selectedSku = item;
    });
  }

  void _resetForm() {
    _formKey.currentState!.reset();
    setState(() {
      _goodsReceiptController.text = '';
      _qualityInspectionController.text = '';
      _numberReceiptController.text = '';
      _actualQuantityReceived.text = '';
      _skuCodeController.text = '';
      _selectedSku = null;
      _pendingDelivery = PendingDeliveryData(
        id: '',
        incomingGoodsNo: '',
        qualityCheckNo: '',
        incomingGoodsUserName: '',
        qualityCheckUserName: '',
        skuCode: '',
        pictureUrlList: [],
      );
    });
  }

  // 查询SKU信息
  Future<void> _searchSkuInfo(
    BuildContext context,
    String? incomingGoodsNo,
    String? qualityCheckNo,
    String? skuCode,
  ) async {
    try {
      if (mounted) {
        LoadingOverlay.show(context);
      }

      // 这里可以添加API调用逻辑
      final response = await HttpUtil.post(
        '/storage/receiveGoodsOperate/getLastOrder',
        data: {
          'whetherLastFinishOrder': true,
          'incomingGoodsNo': incomingGoodsNo,
          'qualityCheckNo': qualityCheckNo,
          'skuCode': skuCode,
        },
      );

      print('response----$response');

      if (!mounted) return; // 检查widget是否仍然挂载

      if (response.data != null) {
        setState(() {
          _pendingDelivery = PendingDeliveryData.fromJson(response.data);
          // skuDataList = [PendingDeliveryData.fromJson(response.data)];
          _qualityInspectionController.text =
              _pendingDelivery?.qualityCheckNo ?? '';
          _goodsReceiptController.text =
              _pendingDelivery?.incomingGoodsNo ?? '';
          _skuCodeController.text = _pendingDelivery?.skuCode ?? '';
        });
        // 自动对焦到实收数量输入框
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            _actualQuantityReceivedFocusNode.requestFocus();
          }
        });
      }

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('查询成功！'), duration: Duration(seconds: 1)),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('查询失败: $e'), duration: Duration(seconds: 1)),
        );
      }
    } finally {
      LoadingOverlay.hide();
    }
  }

  // 提交表单
  Future<void> _submitForm(
    BuildContext context,
    // String id,
    // num actualReceiveNum,
  ) async {
    try {
      if (_actualQuantityReceived.text.isEmpty == true ||
          _actualQuantityReceived.text == '0') {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('请输入实收数量'), duration: Duration(seconds: 1)),
          );
        }
        return;
      }

      if (mounted) {
        LoadingOverlay.show(context);
      }

      // 这里可以添加API调用逻辑
      final response = await HttpUtil.post(
        '/storage/receiveGoodsOperate/commit',
        // data: {'id': id, 'actualReceiveNum': actualReceiveNum},
        data: {
          'id': _pendingDelivery?.id,
          'actualReceiveNum': _actualQuantityReceived.text,
        },
      );

      print('提交响应: $response');

      if (!mounted) return; // 检查widget是否仍然挂载

      if (response.code == 200) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('提交成功！'), duration: Duration(seconds: 3)),
        );
        // x先保留
        // _resetForm();
      } else {
        print('提交失败: ${response.message}');
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('提交失败: ${response.message}'),
              duration: Duration(seconds: 2),
            ),
          );
        }
        // _resetForm();
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('提交失败: $e'), duration: Duration(seconds: 1)),
        );
      }
    } finally {
      _actualQuantityReceivedFocusNode.unfocus();
      LoadingOverlay.hide();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('点数收货')),
      body: Padding(
        padding: EdgeInsets.all(1),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              // 收货单号

              // 来货单号
              Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('来货单', isRequired: false),
                    ),
                  ),
                  Expanded(
                    flex: 6,
                    child: Align(
                      alignment: Alignment.center,
                      child: TextFormField(
                        controller: _goodsReceiptController,
                        readOnly: _hasValidData,
                        decoration: _buildInputDecoration(
                          hintText: '',
                          controller: _goodsReceiptController,
                          suffixIcon: ValueListenableBuilder<TextEditingValue>(
                            valueListenable: _goodsReceiptController,
                            builder: (context, value, child) {
                              return (value.text.isEmpty ||
                                      (_pendingDelivery?.id?.isNotEmpty ??
                                          true))
                                  ? SizedBox.shrink()
                                  : IconButton(
                                      icon: Icon(Icons.clear, size: 20),
                                      onPressed: () {
                                        _goodsReceiptController.clear();
                                      },
                                    );
                            },
                          ),
                        ),
                        focusNode: _goodReceiptFocusNode,
                        onFieldSubmitted: (value) {
                          if (_goodsReceiptController.text.isEmpty) {
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(
                                content: Text('请输入来货单'),
                                duration: Duration(seconds: 1),
                              ),
                            );
                            return;
                          }
                          _searchSkuInfo(
                            context,
                            _goodsReceiptController.text,
                            '',
                            '',
                          );
                          print('回车执行');
                        },
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 3,
                    child: Align(
                      alignment: Alignment.topRight,
                      child: Text(
                        '来货员: ${_pendingDelivery?.incomingGoodsUserName}',
                      ),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('质检单', isRequired: false),
                    ),
                  ),
                  Expanded(
                    flex: 6,
                    child: Align(
                      alignment: Alignment.center,
                      child: TextFormField(
                        controller: _qualityInspectionController,
                        readOnly: _hasValidData,
                        decoration: _buildInputDecoration(
                          hintText: '',
                          controller: _qualityInspectionController,
                          suffixIcon: ValueListenableBuilder<TextEditingValue>(
                            valueListenable: _qualityInspectionController,
                            builder: (context, value, child) {
                              return (value.text.isEmpty ||
                                      (_pendingDelivery?.id?.isNotEmpty ??
                                          true))
                                  ? SizedBox.shrink()
                                  : IconButton(
                                      icon: Icon(Icons.clear, size: 20),
                                      onPressed: () {
                                        _qualityInspectionController.clear();
                                      },
                                    );
                            },
                          ),
                        ),
                        focusNode: _qualityInspectionFocusNode,
                        onFieldSubmitted: (value) {
                          if (_qualityInspectionController.text.isEmpty) {
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(
                                content: Text('请输入质检单'),
                                duration: Duration(seconds: 1),
                              ),
                            );
                            return;
                          }
                          _searchSkuInfo(
                            context,
                            '',
                            _qualityInspectionController.text,
                            '',
                          );
                          print('回车执行');
                        },
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 3,
                    child: Align(
                      alignment: Alignment.topRight,
                      child: Text(
                        '质检员: ${_pendingDelivery?.qualityCheckUserName}',
                      ),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),

              Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('SKU编码', isRequired: false),
                    ),
                  ),
                  Expanded(
                    flex: 3,
                    child: Align(
                      alignment: Alignment.center,
                      child: TextFormField(
                        controller: _skuCodeController,
                        readOnly: _hasValidData,
                        decoration: _buildInputDecoration(
                          hintText: '',
                          controller: _skuCodeController,
                          suffixIcon: ValueListenableBuilder<TextEditingValue>(
                            valueListenable: _skuCodeController,
                            builder: (context, value, child) {
                              return (value.text.isEmpty ||
                                      (_pendingDelivery?.id?.isNotEmpty ??
                                          true))
                                  ? SizedBox.shrink()
                                  : IconButton(
                                      icon: Icon(Icons.clear, size: 20),
                                      onPressed: () {
                                        _skuCodeController.clear();
                                      },
                                    );
                            },
                          ),
                        ),
                        focusNode: _skuCodeFocusNode,
                        onFieldSubmitted: (value) {
                          if (_skuCodeController.text.isEmpty) {
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(
                                content: Text('请输入SKU编码'),
                                duration: Duration(seconds: 1),
                              ),
                            );
                            return;
                          }
                          _searchSkuInfo(
                            context,
                            '',
                            '',
                            _skuCodeController.text,
                          );
                          print('回车执行');
                        },
                      ),
                    ),
                  ),
                  // 按钮部分
                  (!_hasValidData)
                      ? Expanded(
                          flex: 1,
                          child: Align(
                            alignment: Alignment.centerRight,
                            child: ElevatedButton(
                              onPressed: () {
                                if (_skuCodeController.text.isEmpty) {
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(
                                      content: Text('请输入SKU编码'),
                                      duration: Duration(seconds: 1),
                                    ),
                                  );
                                  return;
                                }
                                _searchSkuInfo(
                                  context,
                                  '',
                                  '',
                                  _skuCodeController.text,
                                );
                                // _getInfoRequest();
                              },
                              style: ElevatedButton.styleFrom(
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(2),
                                ),
                                padding: EdgeInsets.all(12),
                                minimumSize: Size(0, 0),
                                backgroundColor: Colors.blue,
                                foregroundColor: Colors.white,
                                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                              ),

                              child: Text('查询'),
                            ),
                          ),
                        )
                      : SizedBox(width: 0),
                ],
              ),

              _hasValidData &&
                      (_pendingDelivery?.pictureUrlList?.isNotEmpty == true)
                  ? const Divider(
                      height: 2, // 容器总高度2像素
                      thickness: 1, // 分割线厚度5像素
                      indent: 0, // 左侧缩进20像素
                      endIndent: 0, // 右侧无缩进
                      color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
                    )
                  : SizedBox(width: 0),
              (_pendingDelivery?.pictureUrlList?.isNotEmpty == true)
                  ? Row(
                      children: [
                        Expanded(
                          flex: 2,
                          child: Align(
                            alignment: Alignment.center,
                            child: GestureDetector(
                              onTap: () {
                                _showImagePreview(
                                  context,
                                  _pendingDelivery!.pictureUrlList!.first,
                                );
                              },
                              child: Image.network(
                                _pendingDelivery!.pictureUrlList!.first,
                                width: 100,
                                height: 100,
                                fit: BoxFit.cover,
                                errorBuilder: (context, error, stackTrace) {
                                  return Icon(
                                    Icons.image_not_supported,
                                    size: 50,
                                  );
                                },
                              ),
                            ),
                          ),
                        ),
                      ],
                    )
                  : SizedBox(),
              (_pendingDelivery?.id?.isNotEmpty == true)
                  ? const Divider(
                      height: 2, // 容器总高度2像素
                      thickness: 1, // 分割线厚度5像素
                      indent: 0, // 左侧缩进20像素
                      endIndent: 0, // 右侧无缩进
                      color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
                    )
                  : SizedBox(),

              // 选择sku后展示的数据
              _hasValidData
                  ? Row(
                      children: [
                        Expanded(
                          flex: 4,
                          child: Align(
                            alignment: Alignment.centerLeft,
                            child: _buildLabel(
                              '应收数量:${_pendingDelivery?.expectReceiveNum}',
                              isRequired: false,
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 4,
                          child: Align(
                            alignment: Alignment.centerLeft,
                            child: _buildLabel('已打印数:', isRequired: false),
                          ),
                        ),
                      ],
                    )
                  : SizedBox(),
              (_pendingDelivery?.id?.isNotEmpty == true)
                  ? const Divider(
                      height: 2, // 容器总高度2像素
                      thickness: 1, // 分割线厚度5像素
                      indent: 0, // 左侧缩进20像素
                      endIndent: 0, // 右侧无缩进
                      color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
                    )
                  : SizedBox(),
              // 选择sku后展示的数据
              (_pendingDelivery?.id?.isNotEmpty == true)
                  ? Row(
                      children: [
                        Expanded(
                          flex: 1,
                          child: Align(
                            alignment: Alignment.centerLeft,
                            child: _buildLabel('实收数量', isRequired: true),
                          ),
                        ),
                        Expanded(
                          flex: 3,
                          child: Align(
                            alignment: Alignment.centerLeft,
                            child: TextFormField(
                              controller: _actualQuantityReceived,
                              decoration: _buildInputDecoration(
                                hintText: '',
                                controller: _actualQuantityReceived,
                                suffixIcon:
                                    ValueListenableBuilder<TextEditingValue>(
                                      valueListenable: _actualQuantityReceived,
                                      builder: (context, value, child) {
                                        return value.text.isEmpty
                                            ? SizedBox.shrink()
                                            : IconButton(
                                                icon: Icon(
                                                  Icons.clear,
                                                  size: 20,
                                                ),
                                                onPressed: () {
                                                  _actualQuantityReceived
                                                      .clear();
                                                },
                                              );
                                      },
                                    ),
                              ),
                              focusNode: _actualQuantityReceivedFocusNode,
                              onFieldSubmitted: (value) {
                                //  _getInfoRequest();

                                print('回车执行');
                              },
                            ),
                          ),
                        ),
                      ],
                    )
                  : SizedBox(),
              (_pendingDelivery?.id?.isNotEmpty == true)
                  ? const Divider(
                      height: 2, // 容器总高度2像素
                      thickness: 1, // 分割线厚度5像素
                      indent: 0, // 左侧缩进20像素
                      endIndent: 0, // 右侧无缩进
                      color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
                    )
                  : SizedBox(),
              // 选择sku后展示的数据
              (_pendingDelivery?.id?.isNotEmpty == true)
                  ? Row(
                      children: [
                        Expanded(
                          flex: 1,
                          child: Align(
                            alignment: Alignment.centerLeft,
                            child: _buildLabel('补打数量', isRequired: false),
                          ),
                        ),
                        Expanded(
                          flex: 3,
                          child: Align(
                            alignment: Alignment.centerLeft,
                            child: TextFormField(
                              controller: _numberReceiptController,
                              decoration: _buildInputDecoration(
                                hintText: '',
                                controller: _numberReceiptController,
                                suffixIcon:
                                    ValueListenableBuilder<TextEditingValue>(
                                      valueListenable: _numberReceiptController,
                                      builder: (context, value, child) {
                                        return value.text.isEmpty
                                            ? SizedBox.shrink()
                                            : IconButton(
                                                icon: Icon(
                                                  Icons.clear,
                                                  size: 20,
                                                ),
                                                onPressed: () {
                                                  _numberReceiptController
                                                      .clear();
                                                },
                                              );
                                      },
                                    ),
                              ),
                              focusNode: _numberReceiptFocusNode,
                              onFieldSubmitted: (value) {
                                //  _getInfoRequest();

                                print('回车执行');
                              },
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: Align(
                            alignment: Alignment.centerRight,
                            child: ElevatedButton(
                              onPressed: () {
                                // _getInfoRequest();
                              },
                              style: ElevatedButton.styleFrom(
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(2),
                                ),
                                padding: EdgeInsets.all(12),
                                backgroundColor: Colors.blue,
                                foregroundColor: Colors.white,
                                minimumSize: Size(0, 0),
                                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                              ),

                              child: Text('补打'),
                            ),
                          ),
                        ),
                      ],
                    )
                  : SizedBox(),
              (_pendingDelivery?.id?.isNotEmpty == true)
                  ? const Divider(
                      height: 2, // 容器总高度2像素
                      thickness: 1, // 分割线厚度5像素
                      indent: 0, // 左侧缩进20像素
                      endIndent: 0, // 右侧无缩进
                      color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
                    )
                  : SizedBox(),

              // SKU列表显示区域
              if (!_hasValidData) ...[
                const Divider(
                  height: 2,
                  thickness: 1,
                  indent: 0,
                  endIndent: 0,
                  color: Color.fromARGB(255, 109, 108, 108),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    'SKU列表 (${skuDataList.length}条数据)',
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                ),
                Expanded(child: _buildSkuList()),
              ],
            ],
          ),
        ),
      ),
      bottomNavigationBar: DecoratedBox(
        decoration: BoxDecoration(color: const Color.fromARGB(255, 77, 76, 76)),
        child: SizedBox(
          width: double.infinity,
          height: 50,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 4.0),
            child: Row(
              children: [
                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: OutlinedButton(
                      onPressed: () {
                        // 取消操作，重置表单
                        _resetForm();
                        // final formState = context
                        //     .findAncestorStateOfType<IncomingGoodsFormState>();
                        // formState?._resetForm();
                      },
                      style: OutlinedButton.styleFrom(
                        foregroundColor: Colors.white,
                        backgroundColor: Colors.grey[600],
                        side: BorderSide.none,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 1,
                      ),
                      child: const Text('清除'),
                    ),
                  ),
                ),
                const SizedBox(width: 4),
                Expanded(
                  child:
                      (_pendingDelivery?.id == null ||
                          _pendingDelivery!.id!.isEmpty)
                      ? Text('')
                      : SizedBox(
                          height: 40,
                          child: ElevatedButton(
                            onPressed: () {
                              showDialog(
                                context: context,
                                builder: (context) => AlertDialog(
                                  title: Text('确认提交'),
                                  content: Text('是否确认提交？'),
                                  actions: [
                                    TextButton(
                                      onPressed: () =>
                                          Navigator.of(context).pop(false),
                                      child: const Text('取消'),
                                    ),
                                    TextButton(
                                      onPressed: () {
                                        Navigator.of(context).pop();
                                        //_submitForm(context);
                                      },
                                      child: const Text('确认'),
                                    ),
                                  ],
                                ),
                              );
                            },
                            style: ElevatedButton.styleFrom(
                              backgroundColor: const Color.fromARGB(
                                255,
                                7,
                                219,
                                113,
                              ),
                              foregroundColor: Colors.white,
                              textStyle: const TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                              ),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                              elevation: 3,
                              // shadowColor: Colors.blue.withOpacity(0.3),
                            ),
                            child: const Text('全部打印'),
                          ),
                        ),
                ),
                const SizedBox(width: 4),
                Expanded(
                  child:
                      (_pendingDelivery?.id == null ||
                          _pendingDelivery!.id!.isEmpty)
                      ? Text('')
                      : SizedBox(
                          height: 40,
                          child: ElevatedButton(
                            onPressed: () {
                              _submitForm(context);
                              // final formState = context
                              //     .findAncestorStateOfType<IncomingGoodsFormState>();
                              // formState?._submitForm();
                              // _submitForm(context);

                              // showDialog(
                              //   context: context,
                              //   builder: (context) => AlertDialog(
                              //     title: Text('确认提交'),
                              //     content: Text('是否确认提交？'),
                              //     actions: [
                              //       TextButton(
                              //         onPressed: () =>
                              //             Navigator.of(context).pop(false),
                              //         child: const Text('取消'),
                              //       ),
                              //       TextButton(
                              //         onPressed: () {
                              //           _submitForm(context);
                              //           Navigator.of(context).pop();
                              //         },
                              //         child: const Text('确认'),
                              //       ),
                              //     ],
                              //   ),
                              // );
                            },
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue[600],
                              foregroundColor: Colors.white,
                              textStyle: const TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                              ),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                              elevation: 3,
                              // shadowColor: Colors.blue.withOpacity(0.3),
                            ),
                            child: const Text('提交'),
                          ),
                        ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildSkuList() {
    // print('🏗️ 构建SKU列表，数据量: ${skuDataList.length}, 加载中: $_isLoading');

    // 如果没有数据，创建测试数据来验证滚动
    // if (skuDataList.isEmpty && !_isLoading) {
    //   print('📋 没有真实数据，创建测试数据来验证滚动监听器...');
    //   return ListView.builder(
    //     controller: _scrollController,
    //     itemCount: 50, // 创建50个测试项目
    //     itemBuilder: (context, index) {
    //       return Container(
    //         height: 80,
    //         margin: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
    //         decoration: BoxDecoration(
    //           color: Colors.blue[50],
    //           border: Border.all(color: Colors.blue[200]!),
    //           borderRadius: BorderRadius.circular(8),
    //         ),
    //         child: ListTile(
    //           leading: Icon(Icons.inventory_2, color: Colors.blue),
    //           title: Text('测试SKU项目 #${index + 1}'),
    //           subtitle: Text('SKU编码: TEST-${index.toString().padLeft(3, '0')}'),
    //           trailing: ElevatedButton(
    //             onPressed: () {
    //               print('点击了测试项目 #${index + 1}');
    //             },
    //             child: Text('选择'),
    //           ),
    //         ),
    //       );
    //     },
    //   );
    // }

    return ListView.separated(
      itemCount: skuDataList.length + (_isLoading ? 1 : 0), // 添加加载指示器
      //itemCount: 50,
      controller: _scrollController,
      separatorBuilder: (context, index) =>
          Divider(color: Colors.grey, height: 1),
      itemBuilder: (context, index) {
        // 如果是最后一项且正在加载，显示加载指示器
        if (index == skuDataList.length) {
          return Container(
            padding: EdgeInsets.all(16),
            alignment: Alignment.center,
            child: CircularProgressIndicator(),
          );
        }

        final sku = skuDataList[index]; // 直接使用 PendingDeli
        return Container(
          padding: EdgeInsets.symmetric(vertical: 2, horizontal: 2),
          child: Row(
            children: [
              // 图片部分
              (sku.pictureUrlList?.isNotEmpty == true)
                  ? GestureDetector(
                      onTap: () {
                        _showImagePreview(context, sku.pictureUrlList!.first);
                      },
                      child: Image.network(
                        sku.pictureUrlList!.first,
                        width: 50,
                        height: 50,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return Icon(Icons.image_not_supported, size: 50);
                        },
                      ),
                    )
                  : Icon(Icons.inventory_2, size: 50),
              SizedBox(width: 12),
              // 文本信息部分
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'SKU编码: ${sku.skuCode ?? ''}',
                      style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                    ),
                  ],
                ),
              ),
              // 按钮部分
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                onPressed: () {
                  // 选择SKU项目
                  _selectItem(sku);
                  // print('Selected SKU: ${sku.skuName} (ID: ${sku.id})');
                },
                child: Text('选择'),
              ),
            ],
          ),
        );
      },
    );
  }

  // 显示图片预览对话框
  void _showImagePreview(BuildContext context, String imageUrl) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          child: Stack(
            children: [
              Center(
                child: InteractiveViewer(
                  panEnabled: true, // 允许拖拽
                  boundaryMargin: EdgeInsets.all(20),
                  minScale: 0.1,
                  maxScale: 6.0,
                  child: SizedBox(
                    width: MediaQuery.of(context).size.width * 0.9,
                    child: Image.network(
                      imageUrl,
                      fit: BoxFit.contain,
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          padding: EdgeInsets.all(20),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(Icons.error, size: 50, color: Colors.white),
                              SizedBox(height: 10),
                              Text(
                                '图片加载失败',
                                style: TextStyle(color: Colors.white),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                  ),
                ),
              ),
              Positioned(
                top: 40,
                right: 20,
                child: GestureDetector(
                  onTap: () => Navigator.of(context).pop(),
                  child: Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Colors.black54,
                      shape: BoxShape.circle,
                    ),
                    child: Icon(Icons.close, color: Colors.white, size: 24),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  // 构建标签文本
  Widget _buildLabel(String text, {bool isRequired = false}) {
    return SizedBox(
      // width: 200,
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 2),
        child: Text(
          text,
          style: TextStyle(
            fontWeight: FontWeight.w500,
            fontSize: 16,
            color: isRequired ? Colors.red : Colors.grey[700],
          ),
        ),
      ),
    );
  }

  // 构建输入框装饰
  InputDecoration _buildInputDecoration({
    required String hintText,
    required TextEditingController controller,
    Widget? suffixIcon,
  }) {
    print('controller ${controller.text}');
    return InputDecoration(
      hintText: hintText,
      contentPadding: EdgeInsets.zero, // 设置上下左右内边距都为0
      // prefixIcon: Icon(prefixIcon, color: Colors.grey[600]),
      suffixIcon: suffixIcon,
      hintStyle: TextStyle(color: Colors.grey[500]),
      // isDense: true 属性用于减少输入框的垂直高度，使其更紧凑
      // 当设置为 true 时，会减少内边距，让输入框看起来更小更密集
      // 适用于需要节省空间或创建更紧凑布局的场景
      // isDense: true,
      filled: true,
      fillColor: Colors.grey[50],

      // suffixIcon: controller.text.isNotEmpty
      //             ? IconButton(
      //                 icon: Icon(Icons.clear, size: 20),
      //                 onPressed: () {
      //                   controller.clear();
      //                   // 需要通知父组件状态更新
      //                   if (mounted) {
      //                     setState(() {});
      //                   }
      //                 },
      //               )
      //             : null,
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.grey[300]!),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.grey[300]!),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.blue, width: 2),
      ),
      errorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.red),
      ),
      focusedErrorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.red, width: 2),
      ),
    );
  }
}

// 收货数据类
class PendingDeliveryData {
  final String? id;
  final String? incomingGoodsNo;
  final String? qualityCheckNo;
  final String? incomingGoodsUserName;
  final String? qualityCheckUserName;
  final String? skuCode;
  final List<String>? pictureUrlList;
  final num? actualReceiveNum;
  final num? expectReceiveNum;

  PendingDeliveryData({
    this.id,
    this.incomingGoodsNo,
    this.qualityCheckNo,
    this.incomingGoodsUserName,
    this.qualityCheckUserName,
    this.skuCode,
    this.pictureUrlList,
    this.actualReceiveNum,
    this.expectReceiveNum,
  });

  factory PendingDeliveryData.fromJson(Map<String, dynamic> json) {
    return PendingDeliveryData(
      id: json['id']?.toString(),
      qualityCheckNo: json['qualityCheckNo']?.toString(),
      incomingGoodsNo: json['incomingGoodsNo']?.toString(),
      incomingGoodsUserName: json['incomingGoodsUserName']?.toString(),
      qualityCheckUserName: json['qualityCheckUserName']?.toString(),
      skuCode: json['skuCode']?.toString(),
      pictureUrlList: json['pictureUrlList'] != null
          ? List<String>.from(
              json['pictureUrlList'].map((x) => x?.toString() ?? ''),
            )
          : null,
      actualReceiveNum: json['actualReceiveNum'] != null
          ? num.tryParse(json['actualReceiveNum'].toString())
          : null,
      expectReceiveNum: json['expectReceiveNum'] != null
          ? num.tryParse(json['expectReceiveNum'].toString())
          : null,
    );
  }
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'incomingGoodsNo': incomingGoodsNo,
      'qualityCheckNo': qualityCheckNo,
      'incomingGoodsUserName': incomingGoodsUserName,
      'qualityCheckUserName': qualityCheckUserName,
      'skuCode': skuCode,
      'pictureUrlList': pictureUrlList,
      'actualReceiveNum': actualReceiveNum,
      'expectReceiveNum': expectReceiveNum,
    };
  }
}
